<template>
  <el-container class="login-container">
    <el-main>
      <video autoplay muted loop>
        <source src="~@/assets/video/index.mp4" />
      </video>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        id="login"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title">人才管理系统</h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            status-icon="true"
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>

        <el-form-item prop="code">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="code"
            v-model="loginForm.captcha"
            placeholder="请输入验证码"
            name="captcha"
            type="text"
            size="small"
            tabindex="1"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
        <el-image
          :src="codeImage"
          style="width: 200px; height: 40px; top: -5px; left: 10px"
        >
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>
        <el-link
          type="primary"
          style="left: 40px; font-size: 20px; top: -20px"
          @click="refreshCode"
          >看不清？点击刷新</el-link
        >
        <el-button
          :loading="loading"
          type="primary"
          style="width: 100%; margin-bottom: 50px; width: 220px"
          @click.native.prevent="handleLogin"
          >登录</el-button
        >
        <el-button
          :loading="loading"
          type="success"
          style="
            width: 100%;
            margin-bottom: 50px;
            margin-left: 2px;
            width: 220px;
          "
          @click="dialogFormVisible = true"
          >注册</el-button
        >
      </el-form>
      <!-- 注册 -->
      <el-dialog
        title="申请企业账号"
        :visible.sync="dialogFormVisible"
        custom-class="logup"
        center
      >
        <el-form :model="form" :rules="rules">
          <el-form-item
            label="注册人"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="form.name"
              prefix-icon="el-icon-service"
              autocomplete="off"
              name="name"
              style="width: 300px; color: black"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="注册账号"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              prefix-icon="el-icon-user"
              v-model="form.username"
              autocomplete="on"
              style="width: 300px"
              name="username"
              placeholder="请输入用户名"
              @blur="checkName()"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="注册密码"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input
              prefix-icon="el-icon-lock"
              v-model="form.password"
              show-password
              autocomplete="off"
              style="width: 300px"
              name="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="公司名称"
            :label-width="formLabelWidth"
            prop="companyName"
          >
            <el-input
              v-model="form.companyName"
              prefix-icon="el-icon-office-building"
              autocomplete="off"
              style="width: 300px"
              name="companyName"
              placeholder="请输入公司名称"
              @blur="companyVer()"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="公司地址"
            :label-width="formLabelWidth"
            prop="companyAddress"
          >
            <el-input
              type="textarea"
              v-model="form.companyAddress"
              style="width: 300px"
              name="companyAddress"
              placeholder="请输入公司地址"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="mobile"
          >
            <el-input
              prefix-icon="el-icon-mobile-phone"
              v-model="form.mobile"
              name="mobile"
              autocomplete="off"
              style="width: 300px"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <!-- 上传营业执照 -->
          <el-form-item label="营业执照" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:9529/dev-api/sys/company/registerPic"
              :show-file-list="false"
              multiple
              drag
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" id="btns">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="logup()">确 定</el-button>
        </span>
        <div id="rightimage"></div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { validUsername } from "@/utils/validate";
import logupapi from "@/api/logup";
import leftImage from "@/assets/images/left.png";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error("请输入正确的用户名"));
      // } else {
      callback();
      //}
    };
    const validatePassword = (rule, value, callback) => {
      let flag = 0;
      for (let i = 0; i < value; i++) {
        if (
          (value[i] >= "a" && value[i] <= "z") ||
          (value[i] >= "A" && value[i] <= "Z")
        )
          flag++;
      }
      if (flag < 2 && value.length < 10) {
        callback(
          new Error("密码长度不能少于10位，且至少有一个字母和一个特殊字符")
        );
      } else {
        callback();
      }
    };
    const validateCaptcha = (rule, value, callback) => {
      callback();
    };
    return {
      loginForm: {
        username: "admin",
        password: "admin123456789",
        captcha: "",
      },
      // 注册信息
      dialogFormVisible: false,
      form: {
        name: "",
        mobile: "",
        companyName: "",
        companyAddress: "",
        imageUrl: "122222222222223",
        username: "",
        password: "",
      },
      formLabelWidth: "100px",
      url: leftImage,
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        captcha: [
          { required: true, trigger: "blur", validator: validateCaptcha },
        ],
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: "密码长度在6到18位", trigger: "blur" },
        ],
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
          { min: 3, max: 15, message: "公司名称在3到15位", trigger: "blur" },
        ],
        companyAddress: [
          { required: true, message: "请输入公司地址", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 10, message: "申请人姓名在2到10位" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号" },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      codeImage: "",
      canLogup: true,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    //用户名检查
    checkName() {
      logupapi.userNameVer(this.form.username).then((response) => {
        let isusername = response.msg;
        if (isusername == false) {
          this.$message.error("用户名已存在");
          this.canLogup = false;
        }
      });
    },
    //公司名检查
    companyVer() {
      logupapi.companyVer(this.form.companyName).then((response) => {
        let isusername = response.msg;
        if (isusername == false) {
          this.$message.error("公司名已存在");
          this.canLogup = false;
        }
      });
    },
    //显示密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let captcha = this.loginForm.captcha;
          let username = this.loginForm.username;
          let password = this.loginForm.password;
          let login = {
            username: username,
            password: password,
            captcha: captcha,
          };
          this.$store
            .dispatch("user/login", login)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery,
              });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
              this.loginForm.captcha = "";
              this.refreshCode();
            });
        } else {
          console.log("登录错误!!");
          return false;
        }
      });
    },
    //刷新验证码
    refreshCode() {
      this.codeImage = "";
      setTimeout(() => {
        this.codeImage = "http://localhost:8888/captcha.jpg";
      }, 10);
    },
    //上传文件
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    //上传前验证文件
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    logup() {
      if (
        this.form.name == "" ||
        this.form.mobile == "" ||
        this.form.companyName == "" ||
        this.form.companyAddress == "" ||
        this.form.username == "" ||
        this.form.password == ""
      )
        this.canLogup = false;

      if (this.canLogup) {
        logupapi
          .logup(this.form)
          .then((response) => {
            this.$message({
              message: "注册成功，请耐心等待管理员审核",
              type: "success",
            });
            this.dialogFormVisible = false;
          })
          .catch((err) => console.log(err));
      } else {
        this.$notify.error({
          title: "错误",
          message: "请完善注册信息",
        });
      }
    },
    toLogin() {
      let container = document.querySelector("#login");
      console.log("login", container.style.marginTop);
      let top = -600;
      let timer = setInterval(() => {
        top += 30;
        if (top >= 150) {
          top = 150;
          clearInterval(timer);
        }
        container.style.marginTop = top + "px";
      }, 100);
    },
  },
  mounted() {
    this.toLogin();
  },
  created() {
    this.codeImage = "http://localhost:8888/captcha.jpg";
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: rgb(248, 242, 242);
$cursor: rgb(10, 10, 10);

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container .login-form {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: $light_gray;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $cursor;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $light_gray inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: $light_gray;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  margin: 0;
  background-color: $bg;
  overflow: hidden;
  .login-form {
    position: relative;
    background-color: rgba(233, 230, 226, 0.4);
    width: 520px;
    max-width: 100%;
    padding: 100px 35px 0;
    margin: -600px auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: absolute;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px 0 40px 0;
      position: relative;
      top: -50px;
      left: 150px;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
<style>
.logup {
  width: 862px;
  height: 754px;
  border-radius: 20px;
  font-size: 20px;
  overflow: hidden;
}
#btns {
  position: relative;
  bottom: 50px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#rightimage {
  width: 298px;
  height: 753px;
  background-image: url("~@/assets/images/left.png");
  /* background-size: cover; */
  background-repeat: no-repeat;
  position: absolute;
  top: 0px;
  right: 0px;
}
body {
  margin: 0;
}
video {
  position: fixed;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
}
</style>
